class DocumentsController < ApplicationController
  before_filter :login_required
  # GET /documents
  # GET /documents.xml
  def index
    @documents = current_user.documents
  end

  # GET /documents/1
  # GET /documents/1.xml
  def show
    @document = Document.find(params[:id])
  end

  # GET /documents/new
  # GET /documents/new.xml
  def new
    @document = Document.new
  end

  # GET /documents/1/edit
  def edit
    @document = Document.find(params[:id])
    @allowed = Document::Max_Attachments - @document.assets.count
  end

  # POST /documents
  # POST /documents.xml
  def create
    @document = Document.new(params[:document])
    
    process_file_uploads(@document)
    @document.user_id = current_user.id

    if @document.save
      flash[:notice] = 'Document was successfully created.'
      redirect_to(@document)
    else
      render :action => "new" 
    end
  end

  # PUT /documents/1
  # PUT /documents/1.xml
  def update
    @document = Document.find(params[:id])
    
    process_file_uploads(@document)

    if @document.update_attributes(params[:document])
      flash[:notice] = 'Document was successfully updated.'
      redirect_to(@document)
    else
      render :action => "edit" 
    end
  end

  # DELETE /documents/1
  # DELETE /documents/1.xml
  def destroy
    @document = Document.find(params[:id])
    @document.destroy
    redirect_to(documents_url)
  end
  
  protected
    def process_file_uploads(document)
        i = 0
        if params[:attachment]
          while params[:attachment]['file_'+i.to_s] != "" && !params[:attachment]['file_'+i.to_s].nil?
            document.assets.build(:data => params[:attachment]['file_'+i.to_s])
            i += 1
          end
        end
    end
end
